package com.vay.de.dang.online.ui.apply;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import java.io.File;
import java.util.List;

import com.bumptech.glide.Glide;
import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.resp.RCodeTableDto;
import com.vay.de.dang.online.resp.RCustomerDataDto;
import com.vay.de.dang.online.resp.RIdCardDto;
import com.vay.de.dang.online.ui.WithBack2Activity;
import com.vay.de.dang.online.util.RequestHelper;
import com.vay.de.dang.online.util.ResponseHelper;
import com.vay.de.dang.online.util.VnContext;
import com.vay.de.dang.online.util.VnUIManager;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.view.DialogMenuOption;
import com.vay.de.dang.online.web.BaseApi;
import com.vay.de.dang.online.web.DeviceApi;
import com.vay.de.dang.online.web.LoanApi;
import com.vay.de.dang.online.web.ReqCallback;
import com.vay.de.dang.online.web.ReqResult;
import com.vay.de.dang.online.web.TableApi;
import com.vay.de.dang.online.R;
import com.vay.de.dang.online.entiy.AppConfigEntity;
import com.vay.de.dang.online.entiy.IncomeRequestEntity;
import com.vay.de.dang.online.entiy.MenuItemEntity;
import com.vay.de.dang.online.entiy.PropertyRuleEntity;
import com.vay.de.dang.online.entiy.RuleStringLengthEntity;
import com.vay.de.dang.online.databinding.ActivityStep3Binding;
import com.vay.de.dang.online.databinding.ViewIdcardItemBinding;

import cc.taylorzhang.singleclick.SingleClickUtil;

public class Step3Activity extends WithBack2Activity {

    final static float f = 1.574f;

    private ActivityStep3Binding binding;
    private IncomeRequestEntity incomeRequest;
    private MenuItemEntity withdrawalMethods;

    private int itemWidth;
    private int itemHeight;
    private String idCardFrontPath;
    private String idCardBackPath;
    private String idCardHandPath;
    private MenuItemEntity idCardType;
    private AppConfigEntity config;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityStep3Binding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setTitleTv(getString(R.string.title_id_info));
        incomeRequest = RequestHelper.currentIncome();

        // 业务埋点
        BaseApi.execBuriedPoint(6000, 6000,
                "完善资料-证件信息", "证件信息页面可见");

        // 证件大小
        itemWidth = (VnApp.getScreenWidth() - VnApp.getDimension(R.dimen.x16) * 4) / 2;
        itemHeight = (int) (itemWidth / f);
        config = VnContext.instance().getAppConfig();

        loadView();
        loadData();

        if (RequestHelper.needQueueIdRule()) {
            BaseApi.idTypeRule(new ReqCallback() {
                @Override
                public void callback(ReqResult value) {
                    if (value.isOk()) {
                        List<PropertyRuleEntity> list = (List<PropertyRuleEntity>) value.result;
                        if (VnUtil.isEmpty(list)) {
                            finish();
                        } else {
                            RequestHelper.setIdRuleList(list);
                        }
                    } else {
                        finish();
                    }
                }
            }.showDialog(true));
        }

        // 证件类型
        TableApi.codeTable(TableApi.ID_TYPE, new ReqCallback() {
            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    List<MenuItemEntity> list = (List<MenuItemEntity>) value.result;
                    loadIdCardType(list.get(0));
                }
            }
        });
    }

    private void loadView() {
        // 取款方式
        binding.withdrawalMethods.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {

                        binding.withdrawalMethods.setContent(bean.getLabel());
                        incomeRequest.setWithdrawalType(VnUtil.toIntValue(bean.getValue()));
                        incomeRequest.setWithdrawalMethod(bean.getValue());
                        incomeRequest.setBelongingBank(bean.getLabel());
                        incomeRequest.setBelongingBankCode(bean.getValue());

                        withdrawalMethods = bean;
                        controlView(bean);
                    })
                    .showChoice(getString(R.string.label_withdrawal_method), TableApi.WITHDRAWAL_TYPE);
        });

        // 银行
        binding.bank.setOnItemClick(() -> {
            withdrawalMethods(1);
        });

        // 电子钱包
       /* binding.eWallet.setOnItemClick(() -> {
            withdrawalMethods(2);
        });

        // 门店
        binding.shopName.setOnItemClick(() -> {
            withdrawalMethods(3);
        });*/

        // ID type
        /*binding.idType.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {
                        loadIdCardType(bean);
                    })
                    .showChoice("ID Type", TableApi.ID_TYPE);
        });*/

        // 性别
        binding.sex.setOnItemClick(() -> {
            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {
                        binding.sex.setContent(bean.getLabel());
                        incomeRequest.setSex(VnUtil.toIntValue(bean.getValue()));
                    })
                    .showChoice(getString(R.string.label_sex), TableApi.GENDER);
        });

        // 根据配置决定UI
        //boolean isGpPhone = config.isGpPhone();
        // 证件信息[身份证正反面、手持身份证]配置：0均不上传、 1上传身份证正反面、 2均上传
        /*if (certInfo == 0) {
            binding.idFLayout.getRoot().setVisibility(View.GONE);
            binding.idBLayout.getRoot().setVisibility(View.GONE);
            binding.idHLayout.getRoot().setVisibility(View.GONE);
        }
        // 正反面
        else if (certInfo == 1) {
            binding.idFLayout.getRoot().setVisibility(View.VISIBLE);
            binding.idBLayout.getRoot().setVisibility(View.VISIBLE);
            binding.idHLayout.getRoot().setVisibility(View.GONE);
        }
        // 均上传
        else if (certInfo == 2) {
            binding.idFLayout.getRoot().setVisibility(View.VISIBLE);
            binding.idBLayout.getRoot().setVisibility(View.VISIBLE);
            binding.idHLayout.getRoot().setVisibility(View.VISIBLE);
        }*/

        // 送审手机号码
        if (config.isGpPhone()) {
            binding.idFLayout.getRoot().setVisibility(View.GONE);
            binding.idBLayout.getRoot().setVisibility(View.GONE);
            binding.idHLayout.getRoot().setVisibility(View.GONE);
        } else {
            binding.idFLayout.getRoot().setVisibility(View.VISIBLE);
            binding.idBLayout.getRoot().setVisibility(View.VISIBLE);
            binding.idHLayout.getRoot().setVisibility(View.VISIBLE);
        }

        // 证件照正面
        SingleClickUtil.onSingleClick(binding.idFLayout.ivImage, view -> {
            Intent intent = new Intent();
            intent.setClass(mActivity, TakeImageActivity.class);
            intent.putExtra("fromType", 0);
            startActivityForResult(intent, 2100);
        });
        binding.idFLayout.label.setText(R.string.id_id_card_f);
        binding.idFLayout.ivImage.setImageResource(R.mipmap.ic_id_card_t1);

        // 证件照反面
        SingleClickUtil.onSingleClick(binding.idBLayout.ivImage, view -> {
            Intent intent = new Intent();
            intent.setClass(mActivity, TakeImageActivity.class);
            intent.putExtra("fromType", 0);
            startActivityForResult(intent, 2101);
        });
        binding.idBLayout.label.setText(R.string.id_id_card_b);
        binding.idBLayout.ivImage.setImageResource(R.mipmap.ic_id_card_t2);

        // 手持证件照
        SingleClickUtil.onSingleClick(binding.idHLayout.ivImage, view -> {
            Intent intent = new Intent();
            intent.setClass(mActivity, TakeImageActivity.class);
            intent.putExtra("fromType", 1);
            startActivityForResult(intent, 2102);
        });
        binding.idHLayout.label.setText(R.string.id_id_card_hand);
        binding.idHLayout.ivImage.setImageResource(R.mipmap.ic_id_card_t3);
    }

    private void loadIdCardType(MenuItemEntity bean) {
        binding.idType.setContent(bean.getLabel());
        idCardType = bean;
        incomeRequest.setIdType(bean.getValue());
        // 根据证件类型设置不同长度
        PropertyRuleEntity rule = findIdCardRule();
        if (rule != null) {
            RuleStringLengthEntity lengthEntity = rule.getStringLength();
            if (lengthEntity != null && lengthEntity.getMax() > 0) {
                binding.idNumber.setLengthFilter(lengthEntity.getMax());
            }
        }
    }

    private void formatSize(ViewIdcardItemBinding vb) {
        vb.bntCamera.getLayoutParams().width = itemWidth;
        vb.bntCamera.getLayoutParams().height = itemHeight;
        vb.exampleIv.getLayoutParams().width = itemWidth;
        vb.exampleIv.getLayoutParams().height = itemHeight;
    }

    private void controlView(MenuItemEntity bean) {
        // 银行
        if ("1".equals(bean.getValue())) {
            binding.bank.setVisibility(View.VISIBLE);
            binding.eWallet.setVisibility(View.GONE);
            binding.shopName.setVisibility(View.GONE);
            binding.account.setVisibility(View.VISIBLE);
        }
    }

    private void withdrawalMethods(int value) {
        if (withdrawalMethods != null) {
            String title = "Bank";
            String typeCode;
            if ("2".equals(withdrawalMethods.getValue())) {
                typeCode = TableApi.ELECTRONIC_WALLET;
                title = "eWallet";
            } else if ("3".equals(withdrawalMethods.getValue())) {
                typeCode = TableApi.STORE_NAME;
                title = "ShopName";
            } else {
                typeCode = TableApi.WITHDRAWAL_METHOD;
            }

            new DialogMenuOption(mActivity)
                    .setOnOptionItemClick(bean -> {
                        incomeRequest.setWithdrawalMethod(bean.getValue());
                        if (value == 1) {
                            binding.bank.setContent(bean.getLabel());
                        } else if (value == 2) {
                            binding.eWallet.setContent(bean.getLabel());
                        } else if (value == 3) {
                            binding.shopName.setContent(bean.getLabel());
                        }
                    })
                    .showChoice(title, typeCode);
        }
    }

    private void loadData() {
        RCustomerDataDto dto = ResponseHelper.customerData;
        if (dto == null) return;

        // 取款类型
        RCodeTableDto tableDto = dto.getWithdrawalType();
        if (tableDto != null) {
            binding.withdrawalMethods.setContent(tableDto.getLabel());
            incomeRequest.setWithdrawalType(VnUtil.toIntValue(tableDto.getValue()));
            withdrawalMethods = ResponseHelper.toOptionItem(tableDto);
            String value = withdrawalMethods.getValue();

            // 取款款类型
            tableDto = dto.getWithdrawalMethod();
            if (tableDto != null) {
                controlView(withdrawalMethods);
                // 银行转账
                if ("1".equals(value)) {
                    binding.bank.setContent(tableDto.getLabel());
                    binding.account.setContent(dto.getBankCardNumber());
                    incomeRequest.setWithdrawalMethod(tableDto.getValue());
                    incomeRequest.setBelongingBank(tableDto.getLabel());
                    incomeRequest.setBelongingBankCode(tableDto.getValue());
                }
                /*// 电子钱包
                else if ("2".equals(value)) {
                    binding.eWallet.setContent(tableDto.getLabel());
                    binding.account.setContent(dto.getBankCardNumber());
                    incomeRequest.setWithdrawalMethod(tableDto.getValue());
                }
                // 线下取款
                else if ("3".equals(value)) {
                    binding.shopName.setContent(tableDto.getLabel());
                    incomeRequest.setWithdrawalMethod(null);
                }*/
            }
        }

        // name
        binding.name.setContent(dto.getName());
        incomeRequest.setName(dto.getName());

        // 证件类型
        tableDto = dto.getIdType();
        if (tableDto != null) {
            binding.idType.setContent(tableDto.getLabel());
            incomeRequest.setIdType(tableDto.getValue());
            idCardType = ResponseHelper.toOptionItem(tableDto);
        }

        // 性别
        tableDto = dto.getSex();
        if (tableDto != null) {
            binding.sex.setContent(tableDto.getLabel());
            incomeRequest.setSex(VnUtil.toIntValue(tableDto.getValue()));
        }

        // 生日
        binding.birthday.setContent(dto.getBirthTime());

        // 证件号码
        binding.idNumber.setContent(dto.getIdNumber());

        // 证件图片
        String idPos = dto.getIdPositive();
        String idPosHttp = ResponseHelper.buildPreview(idPos);
        if (!VnUtil.isEmpty(idPosHttp)) {
            idCardFrontPath = idPos;
            incomeRequest.setIdPositive(idPos);
            Glide.with(mActivity)
                    .load(idPosHttp)
                    .centerCrop()
                    .placeholder(R.mipmap.ic_id_card_t1)
                    .into(binding.idFLayout.ivImage);
        }

        // 证件背面
        String idBack = dto.getIdBack();
        String idBackHttp = ResponseHelper.buildPreview(idBack);
        if (!VnUtil.isEmpty(idPosHttp)) {
            idCardBackPath = idBack;
            incomeRequest.setIdBack(idBack);
            Glide.with(mActivity)
                    .load(idBackHttp)
                    .centerCrop()
                    .placeholder(R.mipmap.ic_id_card_t2)
                    .into(binding.idBLayout.ivImage);
        }

        // 手持证件
        String idHold = dto.getHoldIdImg();
        String idHoldHttp = ResponseHelper.buildPreview(idHold);
        if (!VnUtil.isEmpty(idHoldHttp)) {
            idCardHandPath = idHold;
            incomeRequest.setHoldIdImg(idHold);
            Glide.with(mActivity)
                    .load(idHoldHttp)
                    .centerCrop()
                    .placeholder(R.mipmap.ic_camera_select_1)
                    .into(binding.idHLayout.ivImage);
        }
    }

    @Override
    protected void nextActivity() {

        // 取款方式
        if (!VnUtil.isDropList(binding.withdrawalMethods, "Not empty")) return;
        if (withdrawalMethods == null) {
            showHint("Please Choice withdrawal method");
            return;
        }

        // 银行转账
        if (!VnUtil.isDropList(binding.bank, "Not empty")) return;
        if (!VnUtil.isRuleOk(binding.account,
                RequestHelper.findBaseRule("bankCardNumber"))) {
            mScrollView.post(() -> {
                mScrollView.scrollTo(0, binding.account.getTop());
            });
            return;
        }
        incomeRequest.setBankCardNumber(binding.account.getContent());

        // name
        if (!VnUtil.isRuleOk(binding.name,
                RequestHelper.findBaseRule("firstName"))) return;
        incomeRequest.setName(binding.name.getContent());

        // Id Card Type
        if (idCardType == null) {
            binding.idType.showWarring(getString(R.string.error_invalid_id_type));
            return;
        }

        // 证件号码校验
        PropertyRuleEntity rule = findIdCardRule();
        if (!VnUtil.isRuleOk(binding.idNumber, rule)) return;
        incomeRequest.setIdNumber(binding.idNumber.getContent());

        // 证件正面
        if (binding.idFLayout.getRoot().getVisibility() == View.VISIBLE) {
            if (VnUtil.isEmpty(idCardFrontPath)) {
                showHint(R.string.error_invalid_id_card_front);
                return;
            }
        }

        // 证件背面
        if (binding.idBLayout.getRoot().getVisibility() == View.VISIBLE) {
            if (VnUtil.isEmpty(idCardBackPath)) {
                showHint(R.string.error_invalid_id_card_back);
                return;
            }
        }

        // 手持身份证
        if (binding.idHLayout.getRoot().getVisibility() == View.VISIBLE) {
            if (VnUtil.isEmpty(idCardHandPath)) {
                showHint(R.string.error_invalid_id_card_hand);
                return;
            }
        }

        // 性别
        if (!VnUtil.isDropList(binding.sex, "Not empty")) return;
        // 生日
        if (!VnUtil.isRuleOk(binding.birthday,
                RequestHelper.findBaseRule("birthTime"))) return;
        incomeRequest.setBirthTime(binding.birthday.getContent());

        // 业务埋点
        BaseApi.execBuriedPoint(6099, 6000,
                "证件信息下一步", "证件号码", incomeRequest.getIdNumber());

        // 是否需要运营商验证
        if (config.getTripartiteCertification() == 1) {

            // 记录facebook id
            PhoneAuthActivity.facebookId = incomeRequest.getFacebook();
            PhoneAuthActivity.maxErrorCount = config.getTripartiteCertificationLimit();

            Intent intent = new Intent();
            intent.setClass(mActivity, PhoneAuthActivity.class);
            startActivityForResult(intent, 5000);

        } else {
            commitCustomerData();
        }
    }

    private PropertyRuleEntity findIdCardRule() {
        if (idCardType == null) return null;
        // 证件号码校验
        List<MenuItemEntity> list = TableApi.getCodeTable(TableApi.ID_TYPE);
        if (!VnUtil.isEmpty(list)) {
            int targetIndex = 0;
            for (int index = 0; index < list.size(); index++) {
                MenuItemEntity item = list.get(index);
                if (idCardType.getValue().equals(item.getValue())) {
                    targetIndex = index;
                    break;
                }
            }
            String key = "idType_" + (targetIndex + 1);
            return RequestHelper.findIdRule(key);
        }
        return null;
    }

    private void insertIdCardFImage(String path) {
        if (!VnUtil.isEmpty(path)) {
            idCardFrontPath = path;
            Bitmap src = BitmapFactory.decodeFile(path);
            binding.idFLayout.ivImage.setImageBitmap(src);
            if (config.getOcrState() == 1) {
                LoanApi.orcIdentify(new File(path), new ReqCallback(mActivity) {
                    @Override
                    public void callback(ReqResult value) {
                        if (value.isOk()) {
                            RIdCardDto dto = (RIdCardDto) value.result;
                            binding.name.setContent(dto.getName());
                            binding.idNumber.setContent(dto.getIdCardNo());
                            // 性别
                            binding.birthday.setContent(dto.getBorn());
                        }
                    }
                }.showDialog(true));
            }
        }
    }

    private void insertIdCardBImage(String path) {
        if (!VnUtil.isEmpty(path)) {
            idCardBackPath = path;
            Bitmap src = BitmapFactory.decodeFile(path);
            binding.idBLayout.ivImage.setImageBitmap(src);
        }
    }

    private void insertHandImage(String path) {
        if (!VnUtil.isEmpty(path)) {
            idCardHandPath = path;
            Bitmap src = BitmapFactory.decodeFile(path);
            binding.idHLayout.ivImage.setImageBitmap(src);
        }
    }

    @Override
    public void onBackPressed() {
        // 业务埋点
        BaseApi.execBuriedPoint(6010, 6000,
                "完善资料-证件信息", "证件信息返回");
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        // 证件正面
        if (requestCode == 2100) {
            insertIdCardFImage(findString(data, "_out_path"));
        }
        // 证件背面
        else if (requestCode == 2101) {
            insertIdCardBImage(findString(data, "_out_path"));
        }
        // 手持证件照
        else if (requestCode == 2102) {
            insertHandImage(findString(data, "_out_path"));
        }
        // 运营商验证
        else if (requestCode == 5000) {
            commitCustomerData();
        }
    }

    private void commitCustomerData() {
        // 上传资料
        DeviceApi.uploadCustomerData(3, idCardFrontPath, idCardBackPath, idCardHandPath, null,
                new ReqCallback(mActivity) {
                    @Override
                    public void callback(ReqResult value) {
                        if (value.isOk()) {

                            // 下一页
                            VnUIManager.nextFinancialProduct(mActivity, true);

                            // 同步资料
                            RequestHelper.queryCustomerData(mActivity, false, dto -> {

                            });
                        }
                    }
                }.showDialog(true));
    }
}
